package cn.middle.edge.portal;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.middle.common.basic.enums.Status;
import com.middle.common.result.ApiResponse;
import com.middle.common.result.Page;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.middle.basic.entity.SysRole;
import cn.middle.basic.entity.SysUser;
import cn.middle.basic.service.SysRoleService;
import cn.middle.basic.service.SysUserService;

/**
 * 用户管理
 * 
 * @author KING
 *
 */
@Controller
@RequestMapping("/user")
public class UserController {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	private final static String PREFIX = "sys/user/";

	@Autowired
	private SysUserService userService;

	@Autowired
	private SysRoleService roleService;

	@SaCheckPermission("user:add")
	@SuppressWarnings("unchecked")
	@PostMapping("/add")
	@ResponseBody
	public ApiResponse<String> save(@Valid SysUser user,  Long roleId) {
		logger.info("userInfo {}", user);
		if (!userService.checkLoginName(user.getAccountName())) {
			return ApiResponse.FailCustomWithMessage(String.valueOf(-1000), "登陆名称已被占用！");
		}
		// 设置状态，默认启用
		user.setStatus(Status.Active.code());
		// 创建时间
		user.setCreateTime(new Date());
		user.setUpdateTime(new Date());
		// 密码数据库加密，随机UUID 作为key 密钥
		String key = UUID.randomUUID().toString();
		user.setExpand1(key);
		user.setPassword(SaSecureUtil.aesEncrypt(key, user.getPassword()));
		List<Long> roleIds = new ArrayList<>();
		roleIds.add(roleId);
		userService.saveUserAndRole(user, roleIds);
		return ApiResponse.successWithData("新增系统用户成功！");
	}

	@SaCheckPermission("user:add")
	@GetMapping("/add")
	public String add(ModelMap modelMap) {
		modelMap.put("roleList", roleService.getAll());
		return PREFIX + "add";
	}

	@SaCheckPermission("user:edit")
	@GetMapping("/edit")
	public String edit(@NotNull(message="id不能为空！")Long id, ModelMap modelMap) {
		if (id == null) {
			throw new NullPointerException("传递参数为空！");
		}

		SysUser user = this.userService.getById(id);
		if (user == null) {
			throw new NullPointerException("获取用户信息为空！");
		}
		List<SysRole> roles = roleService.findRolesByUserId(id);
		if (roles != null && !roles.isEmpty()) {
			modelMap.put("role", roles.get(0));
		}
		modelMap.put("roleList", roleService.getAll());
		modelMap.put("user", user);
		return PREFIX + "edit";
	}

	@SaCheckPermission("user:edit")
	@ResponseBody
	@SuppressWarnings("unchecked")
	@PostMapping("/edit")
	public ApiResponse<String> edit(@Valid SysUser user, Long roleId) {
		logger.info("userInfo {}", user);

		if (user.getId() == null) {
			return ApiResponse.FailCustomWithMessage(String.valueOf(-1000), "用户ID为空！");
		}

		SysUser sysUser = userService.getById(user.getId());
		if (sysUser == null) {
			return ApiResponse.FailCustomWithMessage(String.valueOf(-1000), "该系统用户不存在，请刷新界面");
		}

		// 账号名称和编辑的账号名称不一致，需要检查是否已被其它用户占用！
		if (!sysUser.getAccountName().equals(user.getAccountName())) {
			if (!userService.checkLoginName(user.getAccountName()))
				return ApiResponse.FailCustomWithMessage(String.valueOf(-1000), "登陆名称已被占用！");
		}

		// 更新时间
		user.setUpdateTime(new Date());
		List<Long> roleIds = new ArrayList<>();
		roleIds.add(roleId);
		this.userService.updateUserAndRole(sysUser, roleIds);
		return ApiResponse.successWithData("修改系统用户成功！");
	}

	@SaCheckPermission("user:delete")
	@ResponseBody
	@SuppressWarnings("unchecked")
	@GetMapping("/delete")
	public ApiResponse<String> delete(@NotNull(message="id不能为空！")Long id) {
		if (id == null) {
			return ApiResponse.FAIL_WITH_PARAME_MISSING;
		}
		SysUser user = userService.getById(id);
		if (user == null) {
			ApiResponse.FailCustomWithMessage(String.valueOf(-1000), "用户不存在!");
		}
		userService.delete(id);

		return ApiResponse.successWithData("删除成功！");
	}

	@SaCheckLogin
	@ResponseBody
	@GetMapping("/verifyaccountName")
	public boolean verifyaccountName(String accountName) {
		return userService.checkLoginName(accountName);
	}

	@SaCheckPermission("user:list")
	@GetMapping("/list")
	public String list(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
			@RequestParam(value = "limit", defaultValue = "10") Integer limit, String realName, String accountName,
			String phone, Byte status, ModelMap modelMap) {
		Page<SysUser> users = userService.listConditions(pageNum, limit, realName, accountName, phone, status);
		modelMap.put("realName", realName);
		modelMap.put("accountName", accountName);
		modelMap.put("phone", phone);
		modelMap.put("status", status);
		modelMap.put("pageInfo", users);
		return PREFIX + "list";
	}

	@SaCheckLogin
	@GetMapping("/password")
	public String password() {
		return PREFIX + "password";
	}
	
	@SuppressWarnings("unchecked")
	@ResponseBody
	@SaCheckLogin
	@PostMapping("/password")
	public ApiResponse<String> password(@NotBlank(message="原始密码不能为空！")String oldPassword,@NotBlank(message="新密码不能为空！") String newPassword) {
	
		Long userId = Long.parseLong((String) StpUtil.getLoginId());
		SysUser user = this.userService.getById(userId);
		if (user == null) {
			return ApiResponse.FailCustomWithMessage(String.valueOf(-1000), "该系统用户不存在，请检查");
		}

		String decryptPassword = SaSecureUtil.aesEncrypt(user.getExpand1(), oldPassword);
		if (!user.getPassword().equals(decryptPassword)) {
			return ApiResponse.FailCustomWithMessage(String.valueOf(-1000), "原始密码不正确，请您检查！");
		}

		// 密码数据库加密，随机UUID 作为key 密钥
		String key = UUID.randomUUID().toString();
		user.setExpand1(key);
		user.setPassword(SaSecureUtil.aesEncrypt(key, newPassword));
        userService.update(user);
		return ApiResponse.successWithData("修改密码成功！");
	}
    
	@SuppressWarnings("unchecked")
	@SaCheckPermission("role:authorisation")
	@ResponseBody
	@GetMapping("/updateStatus")
	public ApiResponse<String> updateStatus(@NotNull(message="id不能为空！")Long userId){
		
		if (userId == null) {
			return ApiResponse.FAIL_WITH_PARAME_MISSING;
		}
		
		SysUser user = this.userService.getById(userId);
		if (user == null) {
			return ApiResponse.FailCustomWithMessage(String.valueOf(-1000), "该系统用户不存在，请检查");
		}
		
		user.setStatus(Status.find(user.getStatus()) == Status.Active ? Status.DLE.code() : Status.Active.code());
		userService.update(user);
		return ApiResponse.successWithData("状态更新成功！");
	}
}
